package cn.jboa.action;

import cn.jboa.common.Constants;
import cn.jboa.entity.Employee;
import cn.jboa.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import cn.jboa.util.MD5;

public class EmployeeAction extends BaseAction<Employee> {
    private Employee employee;
    private String message;
    private Employee manager;
    private String random;

    @Autowired
    @Qualifier("employeeService")
    private EmployeeService employeeService;

    public String login() {
        Object sessionRandom = this.getSession().get("random");
        if (random == null || !random.equals(sessionRandom)) {
            this.addActionError(this.getText("errors.codeerror"));
            message = this.getText("errors.codeerror");
            return INPUT;
        }

        employee.setPassword(MD5.MD5Encode(employee.getPassword()));
        try {
            employee = employeeService.login(employee);
            manager = employeeService.getManager(employee);
            this.getSession().put(Constants.AUTH_EMPLOYEE, employee);
            this.getSession().put(Constants.AUTH_EMPLOYEE_MANAGER, manager);
            this.getSession().put(Constants.EMPLOYEE_POSITION, employee.getSysPosition().getNameCn());
        } catch (RuntimeException e) {
            this.addActionError(this.getText("errors.invalid.usernameorpassword"));
            message = this.getText("errors.invalid.usernameorpassword");
        }
        if (this.hasActionErrors())
            return INPUT;
        return SUCCESS;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    public Employee getManager() {

        return manager;
    }

    public void setManager(Employee manager) {
        this.manager = manager;
    }
}
